import os
import time
from loguru import logger
# 替换 Tortoise 的默认日志处理器
import logging

log_path = os.path.join(os.getcwd(), 'logs')
if not os.path.exists(log_path):
    os.mkdir(log_path)

log_path_error = os.path.join(log_path, f'{time.strftime("%Y-%m-%d")}_info.log')

logger.add(log_path_error, rotation='50MB', retention='10 days', level='DEBUG', format='{time:YYYY-MM-DD HH:mm:ss} | '
                                                                                       '{level} | {message}',
           encoding='utf-8', enqueue=True, compression='zip')




# 创建一个新的日志处理器  将日志传递给loguru

class LoguruHandler(logging.Handler):
    def emit(self, record):
        # Get corresponding Loguru level if it exists
        try:
            level = logger.level(record.levelname).name
            frame = record.__dict__.get('frame', None)
            if frame:
                logger.opt(depth=1, exception=record.exc_info).log(level, record.getMessage(), stack_info=True)
            else:
                logger.log(level, record.getMessage())
        except Exception as e:
            self.handleError(record)


# 替换 Tortoise 的日志处理器
tortoise_log = logging.getLogger('tortoise')
tortoise_log.setLevel(logging.DEBUG)
tortoise_log.addHandler(LoguruHandler())
